package com.cc.visitor.utils;

import com.cc.alltype.wechat.mpbutton.MenuButton;
import com.cc.alltype.wechat.mpbutton.SubButton;
import com.cc.alltype.wechat.mpbutton.ViewButton;
import com.cc.alltype.wechat.mpbutton.ViewButtonMini;
import com.cc.visitor.entity.wechat.WxAccessToken;
import com.cc.visitor.enums.DevMaterial;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URLEncoder;

@Component
public class CreatMenu {
    @Autowired
    private WxAccessToken wxAccessToken;
    private static final ObjectMapper mapper = new ObjectMapper();

    public void create() throws IOException {
        MenuButton button = new MenuButton();

        // 主菜单第一个按钮 - 没有子菜单
        SubButton sb01 = new SubButton("访客登记");
        sb01.getSub_button().add(new ViewButtonMini("制作访单", DevMaterial.VISITOR_MINI.APPID, "pages/safety-notice/safety-notice"));
        sb01.getSub_button().add(new ViewButtonMini("历史记录", DevMaterial.VISITOR_MINI.APPID, "pages/history/history"));
//        sb01.getSub_button().add(new ViewButtonMini("新用户注册", DevMaterial.VISITOR_MINI.APPID, "pages/register/register"));
        button.getButton().add(sb01);

        ViewButtonMini sb02 = new ViewButtonMini("showa", DevMaterial.VISITOR_MINI.APPID, "pages/mill/mill");
        button.getButton().add(sb02);

        // 多个子菜单项，跳转H5
//        SubButton sb03 = new SubButton("关于");
//        sb03.getSub_button().add(new ViewButtonMini("关于", DevMaterial.VISITOR_MINI.APPID, "pages/about/about"));
//        String register = "https://showawx.xdfznh.club/wxmp/register.html";
//        String registerEncoded = URLEncoder.encode(register);
//        String registerEncodedFull = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + DevMaterial.SHOWA_SERV.APPID + "&redirect_uri=" +
//                registerEncoded + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
//        sb03.getSub_button().add(new ViewButton("register", registerEncodedFull));

        // 单个跳转小程序
        ViewButtonMini sb03 = new ViewButtonMini("关于", DevMaterial.VISITOR_MINI.APPID, "pages/about/about");
        button.getButton().add(sb03);

        String btnString = mapper.writeValueAsString(button);
        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
        String access_token = wxAccessToken.getAccessToken();
        url = url.replace("ACCESS_TOKEN", access_token);
        String result = HttpUtils.postForm(url, btnString,false);
        System.out.println("创建菜单的结果：" + result);
    }

}
